<?php

declare(strict_types=1);

namespace app\api\controller\v1;

use app\api\model\Area;
use app\common\Api;
use app\common\facade\Token;
use app\common\model\PublicStatus;
use app\common\model\Question;
use general\Random;
use general\Tree;
use think\facade\Config;
use think\Request;

class Common extends Api
{

    //刷新token
    public function refreshToken()
    {
        $refreshToken = $this->request->post('refresh_token');

        $refreshToken = Token::get($refreshToken, false);

        if (!$refreshToken || $refreshToken['expire_time'] < time()) {
            $this->error("登录过期,请重新登录");
        }
        $newToken = Random::uuid();
        if ($refreshToken['type'] == 'admin-refresh') {
            $baToken =$this->request->request('batoken', 'batoken');
            if (!$baToken) {
                $this->error('Token 无效');
            }
            Token::delete($baToken);
            Token::set($newToken, 'admin', $refreshToken['user_id'], (int)Config::get('general.admin_token_keep_time'));
        } elseif ($refreshToken['type'] == 'user-refresh') {
            $baUserToken = $this->request->request('token', 'token');
            if (!$baUserToken) {
                $this->error('Token 无效');
            }
            Token::delete($baUserToken);
        
            Token::set($newToken, 'user', $refreshToken['user_id'], (int)Config::get('general.user_token_keep_time'));
        }
        $this->success('', [
            'type'  => $refreshToken['type'],
            'token' => $newToken
        ]);
    }


    /**
     * 省份地区数据
     * @throws Throwable
     */
    public function area()
    {
        $type = $this->request->param('type', 'all');
        if ($type == 'all') {
            $this->success('', get_area_all());
        } else {
            $this->success('', get_area());
        }
    }

}
